package com.bruce.framework;

import com.bruce.framework.protocol.http.HttpClient;
import com.bruce.framework.register.RemoteMapRegister;
import com.bruce.provider.api.HelloService;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;

public class ProxyFactory {

    public static <T> T getProxy(Class interfaceClass){

        Object proxyInstance = Proxy.newProxyInstance(ProxyFactory.class.getClassLoader(),
                new Class[]{interfaceClass},
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) {

                        try {
                            Invocation invocation = new Invocation(interfaceClass.getName(), method.getName(),
                                    method.getParameterTypes(), args);

                            // HttpClient httpClient = new HttpClient();

                            Protocol protocol = ProtocolFactory.getProtocol();

                            // 向远程中心请求地址
                            List<URL> urls = RemoteMapRegister.get(interfaceClass.getName());

                            // 这么多地址，总不能遍历吧
                            // 这里还可能有用户自定义的负载均衡策略
                            URL url = LoadBalance.random(urls);

                            String result = protocol.send(url, invocation);

                            return result;
                        } catch (RpcException e) {
                            return "Oops...";
                        }
                    }
                });

        return (T) proxyInstance;
    }

}
